package io.huaguoguo.connector.process;

import io.huaguoguo.connector.Connector;
import io.huaguoguo.connector.adapter.HttpAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.List;

/**
 * 描述：  <br>
 * CreateDate: 2021/11/26 <br>
 *
 * @author huaguoguo
 */
@Slf4j
public class Http11Process extends SimpleChannelInboundHandler<HttpObject> {

    List<Connector> connectors;

    public Http11Process(List<Connector> connectors) {
        this.connectors = connectors;
    }

    /**
     * 读取和响应http客户端
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断 msg 是不是 httprequest请求
        if(msg instanceof HttpRequest) {
            log.info("客户端地址" + ctx.channel().remoteAddress());
            //获取到
            HttpRequest httpRequest = (HttpRequest) msg;
            //获取uri, 过滤指定的资源
            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())) {
                log.info("请求了 favicon.ico, 不做响应");
                return;
            }
            int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
            for (Connector connector : connectors) {
                if (connector.getPort() == port) {
                    //  根据不同的端口号消息转发给相应的Connector来处理
                    HttpResponse httpResponse = connector.process(httpRequest);
                    //将构建好 response返回
                    ctx.writeAndFlush(httpResponse);
                }
            }

        }
    }
}
